package com.zlm.hp.service;

import android.animation.ValueAnimator;
import android.view.animation.LinearInterpolator;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * 音量淡入
 */
public class FadeIn {

    public static void volumeGradient(final IjkMediaPlayer mediaPlayer,
                                      final float from, final float to) {
        ValueAnimator animator = ValueAnimator.ofFloat(from, to);
        animator.setDuration(6000); // 淡入时间
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator it) {
                float volume = (float) it.getAnimatedValue();
                try {
                    // 此时可能 mediaPlayer 状态发生了改变
                    // ,所以用try catch包裹,一旦发生错误,立马取消
                    mediaPlayer.setVolume(volume, volume);
                } catch (Exception e) {
                    it.cancel();
                }
            }

        });
        animator.start();
    }

    public static void volumeFadeOut(final IjkMediaPlayer mediaPlayer,
                                      final float from, final float to) {
        ValueAnimator animator = ValueAnimator.ofFloat(from, to);
        animator.setDuration(3900); // 淡出时间 接近4秒
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator it) {
                float volume = (float) it.getAnimatedValue();
                try {
                    // 此时可能 mediaPlayer 状态发生了改变
                    // ,所以用try catch包裹,一旦发生错误,立马取消
                    mediaPlayer.setVolume(volume, volume);
                } catch (Exception e) {
                    it.cancel();
                }
            }

        });
        animator.start();
    }
}